package com.zyk.leetcode;

/**
 * @author zhangsan
 * @date 2021/4/4 22:55
 */
public class J43 {

    public static int countDigitOne(int n) {
        if (n == 1) {
            return 1;
        }
        int count = 0;
        for (int i = 1; i <= n; i++) {
            count += get1Count(i);
        }
        return count;
    }

    public static int countDigitOne2(int n) {
        int digit = 1, res = 0;
        int high = n / 10, cur = n % 10, low = 0;
        // 如果/10还有值, 或者当前没算完
        while (high != 0 || cur != 0) {
            if (cur == 0) {
                res += high * digit;
            } else if (cur == 1) {
                res += high * digit + low + 1;
            } else {
                res += (high + 1) * digit;
            }
            low += cur * digit;
            cur = high % 10;
            high /= 10;
            digit *= 10;
        }
        return res;
    }

    public static int get1Count(int num) {
        int count = num % 10 == 1 ? 1 : 0;
        while (num != 0) {
            num /= 10;
            count += num % 10 == 1 ? 1 : 0;
        }
        return count;
    }

    // for test
    public static void main(String[] args) {
        for (int i = 0; i <= 1000; i++) {
            System.out.println(i + " : " + countDigitOne(i));
            System.out.println(i + " : " + countDigitOne2(i));
        }
    }

}
